<?php

namespace App\Console\Commands;

use App\Console\Base;
use App\Models\HallPartnerConfig;
use App\Models\PartnerConfig;
use common\enum\CommonEnum;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class GameApiMaintain extends Base
{
    /**
     * 控制台命令 signature 的名称。
     *
     * @var string
     */
    protected $signature = self::PREFIX . 'gameapimaintain';

    /**
     * 控制台命令说明。
     *
     * @var string
     */
    protected $description = 'GameApiMaintain';

    /**
     * 执行控制台命令。
     *
     * @return mixed
     */
    public function handle()
    {
        $time    = date("Y-m-d H:i:s", time());
        $gameApi = PartnerConfig::select(['partner_id', 'partner_name', 'game_type', 'start_time', 'end_time', 'maintaining'])->get();
        $newData = [];
        //筛选出需要改变维护状态的API
        foreach ($gameApi as $key => $value) {
            $maintaining = $value['maintaining'];
            if (!empty($value['start_time']) && !empty($value['end_time'])) {
                if ($value['start_time'] < $time && $time < $value['end_time']) {
                    $value['maintaining'] = CommonEnum::ENABLED;
                } else {
                    $value['maintaining'] = CommonEnum::DISABLE;
                }
                if ($maintaining != $value['maintaining']) {
                    $newData[] = $value;
                }
            }
        }
        //改变维护状态的API
        try {
            DB::beginTransaction();
            foreach ($newData as $val) {
                $updateData = ['maintaining' => $val['maintaining']];
                PartnerConfig::where(["partner_id" => $val['partner_id'], 'game_type' => $val['game_type']])->update($updateData);
                HallPartnerConfig::where(["partner_id" => $val['partner_id'], "game_type" => $val['game_type']])->update($updateData);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('UpdatePartnerConfig||PartnerConfig Error');
        }
    }
}
